<?php

namespace App\Http\Controllers;

use App\Models\NwYbzBms;
use App\Models\NwYbzDcs;
use App\Models\NwYbzEcs;
use App\Models\NwYbzElb;
use App\Models\NwYbzRds;
use App\Models\NwYbzTxIp;
use App\Models\NwYbzZyj; 
use App\Models\NwYbzCreateAndEdit;
use App\Models\NwYbzDelete;
use App\Models\NwYbzUserInfo;
use App\Models\NwYbzWordOrder;
use App\Models\NwYbzCCE;
use App\Models\NwYbzDDM;
use App\Models\NwYbzDDS;
use App\Models\NwYbzDRS;
use App\Models\NwYbzEVS;
use App\Models\NwYbzRomaConnect;
use App\Models\NwYbzServiceStage;
use App\Models\NwYbzVPC;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Schema;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Log;

class NwYbzZyjController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // public function index()
    // {
    //   $NwYbzZyj = NwYbzZyj::all(); // 查询所有资源集
        
    //   return response()->json($NwYbzZyj); // 返回JSON响应
    // }


    public function index(Request $request)
    {
      return "index";
    }

    // 一本账查询
    public function search_ybz(Request $request)
    {
        // 默认查询所有类型，或根据请求参数指定类型
        $resourceType = $request->input('resourceTypeTbale', 'all');

        // 支持的资源类型列表
        $supportedTypes = [
            'Ecs', 'Rds', 'Bms', 'Dcs', 'Elb', 'TxIp', 'Zyj','CCE','DDM','DDS','DRS','EVS','RomaConnect','ServiceStage','VPC',
        ];
        
        // 确保请求的资源类型合法
        if (!in_array($resourceType, $supportedTypes) && $resourceType !== 'all') {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }

        // 设置每页显示的数量
        $perPage = $request->input('per_page', 10);

        // 初始化查询条件
        $queryParams = $request->except(['page', 'per_page', 'resourceTypeTbale','universalSearch']);

        //获取zyj表中所有数据
        $zyjData = NwYbzZyj::all()->keyBy('resource_set_name');

        // 如果是查询所有类型
        if ($resourceType === 'all') {
            $results = collect(); // 初始化一个空的 Collection 对象来收集所有查询结果
            $total = 0; // 初始化总条目数
            $currentPage = LengthAwarePaginator::resolveCurrentPage(); // 获取当前页码
        
            $universalSearchValue = $request->input('universalSearch');

            foreach ($supportedTypes as $type) {
              //// 排除 Zyj 表
              if ($type === 'Zyj') {
                continue; 
              }
                // 动态实例化模型
                $model = "App\Models\NwYbz{$type}";
                $query = (new $model)::query();
              if ($universalSearchValue) {
                // 创建模型实例
                $modelInstance = new $model();
                // 获取模型的文本类型字段名
                $textFields = Schema::getColumnListing($modelInstance->getTable()); // 注意这里使用实例
                $textFields = array_filter($textFields, function($field) use ($modelInstance, $universalSearchValue) { // 传递$modelInstance 和 $universalSearchValue
                    return in_array(Schema::getColumnType($modelInstance->getTable(), $field), ['string', 'text']);
                });
                // 对所有文本字段添加模糊查询条件
                foreach ($textFields as $field) {
                    $query->orWhere($field, 'like', '%' . $universalSearchValue . '%');
                }
                }else{
                  // 应用筛选条件
                  foreach ($queryParams as $key => $value) {
                    $query->where($key, 'like', '%' . $value . '%');
                  }
                }
        
                // 获取当前类型的结果
                $typeResults = $query->get();
        
                // 更新总条目数
                $total += $typeResults->count();
        
                // 添加资源名
                foreach ($typeResults as $item) {
                    $resourceSetName = $item->resource_set_name;
                    if (isset($zyjData[$resourceSetName])) {
                        $item->resource_name = $zyjData[$resourceSetName]->name;
                    } else {
                        $item->resource_name = null;
                    }
                    $results->push($item);
                }
            }
        
            // 对所有结果进行分页处理
            $currentResults = $results->slice(($currentPage - 1) * $perPage, $perPage)->values();
            $pagedResults = new LengthAwarePaginator($currentResults, $total, $perPage, $currentPage, [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
            ]);
        
            // 构建统一的分页响应
            $meta = [
                'current_page' => $pagedResults->currentPage(),
                'last_page' => $pagedResults->lastPage(),
                'per_page' => $pagedResults->perPage(),
                'total' => $pagedResults->total(),
            ];
        
            return response()->json([
                'data' => $pagedResults->items(),
                'meta' => $meta,
            ]);
              
        } else {
            // 如果是单一类型查询
            $modelClass = "App\Models\NwYbz{$resourceType}";
            $query = (new $modelClass)::query();

            // 应用筛选条件
            foreach ($queryParams as $key => $value) {
                $query->where($key, 'like', '%' . $value . '%');
            }

            // 分页执行查询
            $pagedResults = $query->paginate($perPage);

            // 构建响应数据
            //$results = $pagedResults->items();
            // 构建响应数据并添加 resource_name
            $results = $pagedResults->items();

            if ($resourceType === 'Zyj') {
                $UserInfoData = NwYbzUserInfo::all()->keyBy('resource_name');
                foreach ($results as $item) {
                  $resourceSetName = $item->resource_set_name;
                  if (isset($UserInfoData[$resourceSetName])) {
                      $userInfoItem = $UserInfoData[$resourceSetName];
                      //$item->resource_name = $UserInfoData[$resourceSetName]->name;
                      foreach ($userInfoItem->getAttributes() as $key => $value) {
                        if ($key !== 'resource_name') {
                            $item->{$key} = $value;
                        }
                      }
                  } else {
                      $item->resource_name = null;
                  }
                }
              }else{
                foreach ($results as $item) {
                  $resourceSetName = $item->resource_set_name;
                  if (isset($zyjData[$resourceSetName])) {
                      $item->resource_name = $zyjData[$resourceSetName]->name;
                  } else {
                      $item->resource_name = null;
                  }
                }
              }

            $meta = [
                'current_page' => $pagedResults->currentPage(),
                'last_page' => $pagedResults->lastPage(),
                'per_page' => $pagedResults->perPage(),
                'total' => $pagedResults->total(),
            ];
        }

        return JsonResponse::fromJsonString(json_encode([
            'data' => $results,
            'meta' => $meta,
        ]));
    }

    //资源变更
    public function ybzChange(Request $request)
    {
        try {
            // 默认查询所有类型，或根据请求参数指定类型
            $resourceType = $request->input('resourceTypeTbale', 'UserInfo');
    
            // 支持的资源类型列表
            $supportedTypes = [
                'CreateAndEdit', 'Delete', 'UserInfo', 'WordOrder',
            ];
    
            // 确保请求的资源类型合法
            if (!in_array($resourceType, $supportedTypes) && $resourceType !== 'all') {
                return response()->json(['message' => 'Invalid resource type'], 400);
            }
    
            // 设置每页显示的数量
            $perPage = $request->input('per_page', 10);
    
            // 初始化查询条件
            $queryParams = $request->except(['page', 'per_page', 'resourceTypeTbale']);
    
            // 如果 resourceTypeTbale 是 UserInfo 并且查询参数包含 resource_name，则替换为 resource_set_name
            if ($resourceType === 'CreateAndEdit' && isset($queryParams['resource_name'])) {
                $queryParams['system_name'] = $queryParams['resource_name'];
                unset($queryParams['resource_name']);
            }elseif ($resourceType === 'WordOrder' && isset($queryParams['resource_name'])) {
                $queryParams['resourcessets_othername'] = $queryParams['resource_name'];
                unset($queryParams['resource_name']);
            }elseif ($resourceType === 'Delete' && isset($queryParams['resource_name'])) {
                $queryParams['system_name'] = $queryParams['resource_name'];
                unset($queryParams['resource_name']);
            }

            // 获取zyj表中所有数据
            $zyjData = NwYbzZyj::all()->keyBy('resource_set_name');
    
            // 如果是单一类型查询
            $modelClass = "App\Models\NwYbz{$resourceType}";

            if (!class_exists($modelClass)) {
                return response()->json(['message' => 'Model class not found'], 500);
            }
    
            $query = (new $modelClass)::query();
    
            // 应用筛选条件
            foreach ($queryParams as $key => $value) {
                $query->where($key, 'like', '%' . $value . '%');
            }
    
            // 分页执行查询
            $pagedResults = $query->paginate($perPage);
    
            // 构建响应数据并添加 resource_name
            $results = $pagedResults->items();
            
            // foreach ($results as $item) {
            //     $resourceSetName = $item->resource_set_name;
            //     if (isset($zyjData[$resourceSetName])) {
            //         $item->resource_name = $zyjData[$resourceSetName]->name;
            //     } else {
            //         $item->resource_name = null;
            //     }
            // }
    
            $meta = [
                'current_page' => $pagedResults->currentPage(),
                'last_page' => $pagedResults->lastPage(),
                'per_page' => $pagedResults->perPage(),
                'total' => $pagedResults->total(),
            ];
    
            return JsonResponse::fromJsonString(json_encode([
                'data' => $results,
                'meta' => $meta,
            ]));
        } catch (\Exception $e) {
            Log::error('Error in ybzChange: ' . $e->getMessage());
            return response()->json(['message' => 'Server Error'], 500);
        }
    }

    // 
    public function ybzCurd(Request $request)
    {
        $resourceType = $request->input('resourceTypeTbale');
        $supportedTypes = [
            'CreateAndEdit', 'UserInfo', 'Delete', 'WordOrder'
        ];
    
        if (!in_array($resourceType, $supportedTypes)) {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }
    
        $modelClass = "App\Models\NwYbz{$resourceType}";
    
        // 如果是 UserInfo 类型，检查 resource_name 是否已存在
        if ($resourceType === 'UserInfo') {
            $resourceName = $request->input('resource_name');
            $existingResource = $modelClass::where('resource_name', $resourceName)->first();
            if ($existingResource) {
                return response()->json(['message' => '资源集名称数据已存在'], 400);
            }
        }
    
        $data = $request->except('resourceTypeTbale');
    
        $model = new $modelClass();
        foreach ($data as $key => $value) {
            $model->$key = $value;
        }
        $model->save();
    
        return response()->json(['message' => 'Resource created successfully'], 201);
    }

    //编辑接口
    public function ybzEdit(Request $request)
    {
        // 从请求体中获取所有数据
        $requestData = $request->json()->all();
    
        // 确保请求体中有数据
        if (empty($requestData)) {
            return response()->json(['message' => 'No request data found'], 400);
        }
    
        // 提取resourceTypeTbale
        $resourceType = $requestData['resourceTypeTbale'] ?? null;
    
        $supportedTypes = ['CreateAndEdit', 'UserInfo', 'Delete', 'WordOrder'];
    
        // 验证resourceTypeTbale是否有效
        if (!in_array($resourceType, $supportedTypes)) {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }
    
        // 获取ID
        $id = $requestData['id'] ?? null;
    
        // 确保ID存在
        if (!$id) {
            return response()->json(['message' => 'Missing ID for editing'], 400);
        }
    
        // 移除resourceTypeTbale和id，准备更新的数据
        unset($requestData['resourceTypeTbale'], $requestData['id']);
    
        // 根据resourceTypeTbale确定模型类
        $modelClass = "App\Models\NwYbz{$resourceType}";
    
        // 使用主键查找记录
        $model = $modelClass::find($id);
        if (!$model) {
            return response()->json(['message' => 'Record not found'], 404);
        }
    
        // 更新数据
        foreach ($requestData as $key => $value) {
            $model->$key = $value;
        }
    
        // 保存更新并响应结果
        if ($model->save()) {
            return response()->json(['message' => 'Resource updated successfully'], 200);
        } else {
            return response()->json(['message' => 'Failed to update the resource'], 500);
        }
    }

    //删除接口
    public function ybzDelete(Request $request)
    {
        $resourceType = $request->input('resourceTypeTbale');
        $id = $request->input('id');
        $supportedTypes = [
            'CreateAndEdit', 'UserInfo', 'Delete', 'WordOrder'
        ];
    
        if (!in_array($resourceType, $supportedTypes)) {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }
    
        $modelClass = "App\Models\NwYbz{$resourceType}";

        try {
          // 使用模型类删除记录
          $deleted = $modelClass::destroy($id);
          
          if ($deleted) {
              return response()->json(['message' => 'Resource deleted successfully'], 200);
          } else {
              return response()->json(['message' => 'Resource not found'], 404);
          }
      } catch (\Exception $e) {
          // 记录日志或处理异常
          \Log::error($e);
          return response()->json(['message' => 'Deletion failed'], 500);
      }
    }
}
